package com.primaryedu.utils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.primaryedu.R;
import com.primaryedu.bean.CommentBean;
import com.primaryedu.bean.MicroCourseBean;
import com.primaryedu.bean.NewsBean;
import com.primaryedu.bean.NoticeBean;
import com.primaryedu.bean.RepairBean;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import org.apache.http.util.EncodingUtils;


/**
 * <Pre>
 * <p/>
 * </Pre>
 *
 * @author jun.wang
 * @version 1.0
 *          create by  2016-03-27 17:39
 */

@SuppressLint("SimpleDateFormat")
public class Utils {
    static LayoutInflater inflater;
    //	static GifView ;
    private static AnimationDrawable animationDrawable;
    private static ImageView mHeadGifView;

    /******************************************
     * 初始化请求对话框
     *
     * @param context
     * @return progressDialog
     */
    public static ProgressDialog initRequestDialog(final Context context) {
        ProgressDialog progressDialog = new ProgressDialog(context);
        progressDialog.setMessage(context.getString(R.string.dialog_message));
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setCanceledOnTouchOutside(false);
        return progressDialog;
    }

    public static String getVersionCode(Context context) {
        try {
            String pkName = context.getPackageName();
            String versionName = context.getPackageManager().getPackageInfo(
                    pkName, 0).versionName;
            int versionCode = context.getPackageManager()
                    .getPackageInfo(pkName, 0).versionCode;
            return versionCode + "";
        } catch (Exception e) {
        }

        return "";
    }

    public static String getVersionName(Context context) {
        try {
            String pkName = context.getPackageName();
            String versionName = context.getPackageManager().getPackageInfo(
                    pkName, 0).versionName;
            int versionCode = context.getPackageManager()
                    .getPackageInfo(pkName, 0).versionCode;
            return versionName + "";
        } catch (Exception e) {
        }

        return "";
    }

    @SuppressWarnings("unused")
    public static File getFileFromServer(String path, ProgressDialog pd) throws IOException {
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            //获取到文件的大小
            pd.setMax(conn.getContentLength());
            InputStream is = conn.getInputStream();
            File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                //获取当前下载�?
                pd.setProgress(total);
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }

    /**
     * ��ȡ��Ļ��С
     *
     * @param activity
     * @return
     * @author Stone
     */
    public static int[] getScreenSize(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;
        int height = dm.heightPixels;
        return new int[]{width, height};
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {  
         /*
    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188、199
    联通：130、131、132、152、155、156、185、186
    电信：133、153、180、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
    */
        String telRegex = "[1][35789]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }

    @SuppressWarnings("unused")
    public static String[] getTags(String tags) {
        if (TextUtils.isEmpty(tags)) {
            return null;
        }

        String[] result = new String[]{};

        try {
            result = tags.split(",");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    //�Ƿ�����WIFI
    public static boolean isWifiConnected(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifiNetworkInfo.isConnected()) {
            return true;
        }

        return false;
    }

    public static String getCurrentDate() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);

        return str;
    }

    public static String getCurrentTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);

        return str;
    }

    public static String getCurrentDateTwo() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);

        return str;
    }

    public static String getSDPath() {
        return Environment.getExternalStorageState();
    }

    public static List<String> getPaths(List<String> paths) {

        for (int i = 0; i < paths.size() - 1; i++) {
            for (int j = paths.size() - 1; j > i; j--) {
                if (paths.get(j).equals(paths.get(i))) {
                    paths.remove(j);
                }
            }
        }

        return paths;
    }

    // 通知列表
    public static List<NoticeBean> getInform(List<NoticeBean> paths) {

        for (int i = 0; i < paths.size() - 1; i++) {
            for (int j = paths.size() - 1; j > i; j--) {
                if (paths.get(j).getId().equals(paths.get(i).getId())) {
                    paths.remove(j);
                }
            }
        }

        return paths;
    }

    // 评论列表
    public static List<CommentBean> getCommonList(List<CommentBean> paths) {

        for (int i = 0; i < paths.size() - 1; i++) {
            for (int j = paths.size() - 1; j > i; j--) {
                if (paths.get(j).getId().equals(paths.get(i).getId())) {
                    paths.remove(j);
                }
            }
        }

        return paths;
    }

    //活动列表
    public static List<NewsBean> getExerciseList(List<NewsBean> paths) {

        for (int i = 0; i < paths.size() - 1; i++) {
            for (int j = paths.size() - 1; j > i; j--) {
                if (paths.get(j).getId().equals(paths.get(i).getId())) {
                    paths.remove(j);
                }
            }
        }

        return paths;
    }

    //微课列表
    public static List<MicroCourseBean> getCourseList(List<MicroCourseBean> paths) {

        for (int i = 0; i < paths.size() - 1; i++) {
            for (int j = paths.size() - 1; j > i; j--) {
                if (paths.get(j).getId().equals(paths.get(i).getId())) {
                    paths.remove(j);
                }
            }
        }

        return paths;
    }

    // 报修列表
    public static List<RepairBean> getRepairList(List<RepairBean> paths) {

        for (int i = 0; i < paths.size() - 1; i++) {
            for (int j = paths.size() - 1; j > i; j--) {
                if (paths.get(j).getId().equals(paths.get(i).getId())) {
                    paths.remove(j);
                }
            }
        }

        return paths;
    }

    public static String getSkinImagePath(String path) {
        if (TextUtils.isEmpty(path)) {
            return "";
        }

        String result = path.split(",")[0];

        return result;
    }

    /**
     * ȡ��Ŀ������
     *
     * @param height
     * @param weight
     * @return
     */
    public static int getBMIWeight(int height) {

        int temp = (int) (height / 3.4);

        float tempHeight = height;
        float result = (tempHeight / 100) * (tempHeight / 100) * 20;
        System.out.println("result=" + result);
        int m = (int) result;
        System.out.println("result=" + m);
        return m;
    }

    public static String getSex(String str) {
        if (str.equals("1")) {
            return "Ů";
        } else {
            return "��";
        }
    }

    public static String getSinaSex(String str) {
        if (str.equals("m")) {
            return "��";
        } else {
            return "Ů";
        }
    }

    /**
     * �õ� 09:10 ʱ��
     *
     * @param time
     * @return
     */
    public static String getTime(long time) {
        SimpleDateFormat format = new SimpleDateFormat("mm:ss");
        Date d1 = new Date(time);
        String t1 = format.format(d1);

        return t1;
    }

    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public static boolean isWifi(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null
                && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }

    // ֻȡ����
    public static String getStrNoReg(String str) {
        String reg = "[^\u4e00-\u9fa5]";
        return str.replaceAll(reg, "");
    }

    // 获取手机设备ID
    public static String getDeviceId(Context context) {
        TelephonyManager TelephonyMgr = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
        String szImei = TelephonyMgr.getDeviceId();

        return szImei;
    }

    /**
     * @return
     * @description 读取assets里面的文件 根据文件名
     */
    public static String getAssets(Context context, String fileName) {
        String result = "";
        try {
            InputStream in = context.getResources().getAssets().open(fileName);
            //获取文件的字节数
            int lenght = in.available();
            //创建byte数组
            byte[] buffer = new byte[lenght];
            //将文件中的数据读到byte数组中
            in.read(buffer);
            result = EncodingUtils.getString(buffer, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private static double EARTH_RADIUS = 6378.137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    public static double GetShortDistance(double lat1, double lng1, double lat2,
                                          double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000d) / 10000d;
        s = s * 1000;
        return s;
    }

    /**
     * 功能：判断字符串是否为空
     *
     * @param str
     * @return
     */
    public static boolean isBlank(String str) {
        if (str == null)
            return true;

        if ("".equals(str))
            return true;

        if ("".equals(str.trim()))
            return true;

        return false;

    }

    /**
     * 照片转byte二进制
     *
     * @param imagepath 需要转byte的照片路径
     * @return 已经转成的byte
     * @throws Exception
     */
    public static byte[] readStream(String imagepath) throws Exception {
        FileInputStream fs = new FileInputStream(imagepath);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while (-1 != (len = fs.read(buffer))) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        fs.close();
        return outStream.toByteArray();
    }

    /**
     * 比较两个日期的大小，日期格式为yyyy-MM-dd
     *yyyy-MM-dd HH:mm 格式（自己可以修改成想要的时间格式）
     * @param str1 the first date
     * @param str2 the second date
     * @return true <br/>false
     */
    public static boolean isDate2Bigger(String str1, String str2) {
        boolean isBigger = false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date dt1 = null;
        Date dt2 = null;
        try {
            dt1 = (Date) sdf.parse(str1);
            dt2 = (Date) sdf.parse(str2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (dt1.getTime() > dt2.getTime()) {
            isBigger = false;
        } else if (dt1.getTime() <= dt2.getTime()) {
            isBigger = true;
        }
        return isBigger;
    }

    /**
     * 判断是否含有emoji表情
     * @param str
     * @return
     */
    public static boolean ContainsEmoji(String str) {//真为含有表情
        int len = str.length();
        for (int i = 0; i < len; i++) {
            if (isEmojiCharacter(str.charAt(i))) {// 如果能匹配,则该字符是Emoji表情
                return true;
            }
        }
        return false;
    }
    private static boolean isEmojiCharacter(char codePoint) {
        return !((codePoint == 0x0) ||
                (codePoint == 0x9) ||
                (codePoint == 0xA) ||
                (codePoint == 0xD) ||
                ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
                ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)));
    }
}
